// log_query_handler
package handler

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"tasty/common"
	"time"
)

type device struct {
	ID        string `json:"id"`
	NAME      string `json:"name"`
	DEVICE_ID string `json:"device_id"`
	IP        string `json:"ip"`
}

func DeviceRegister(c *gin.Context) {
	_log.Add("device register from " + c.ClientIP())

	rs := new(common.OPT_RESULT)
	rs.CODE = "1"

	name := c.Query("name")
	device_id := c.Query("device_id")

	if strings.EqualFold(name, "") {
		rs.CODE = "-1"
		rs.MSG = "name is empty!"
		data, _ := json.Marshal(rs)
		c.JSON(200, data)
		return
	}

	if strings.EqualFold(device_id, "") {
		rs.CODE = "-2"
		rs.MSG = "device_id is empty!"
		data, _ := json.Marshal(rs)
		c.JSON(200, data)
		return
	}

	del_sql := `delete from device where device_id = '%s'`
	sql := `insert into device(name, device_id, ip, register_time) values('%s', '%s', '%s', '%s')`
	o := orm.NewOrm()
	o.Using("default")
	r, err := o.Raw(fmt.Sprintf(del_sql, device_id)).Exec()

	r, err = o.Raw(fmt.Sprintf(sql, name, device_id, c.ClientIP(), time.Now())).Exec()
	if err != nil {
		rs.CODE = "-3"
		rs.MSG = err.Error()
	}

	i, er := r.RowsAffected()
	if er != nil || i <= 0 {
		rs.CODE = "-4"
		rs.MSG = err.Error()
	}

	data, _ := json.Marshal(rs)
	c.JSON(200, data)
}

func DeviceList(c *gin.Context) {
	dvs := make([]*device, 0, 10)

	sql := `select * from device`
	o := orm.NewOrm()
	o.Using("default")

	var ds []orm.Params
	o.Raw(sql).Values(&ds)

	for _, d := range ds {
		dv := new(device)

		dv.ID = d["id"].(string)
		dv.NAME = d["name"].(string)
		dv.IP = d["ip"].(string)
		dv.DEVICE_ID = d["device_id"].(string)

		dvs = append(dvs, dv)
	}

	data, _ := json.Marshal(dvs)
	c.JSON(200, data)
}
